package com.itheima.component;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.findByUsername(username);
        if (user == null)
            return null;

        String password = user.getPassword();
        String userUsername = user.getUsername();
        //权限和角色集合
        List<GrantedAuthority> list = new ArrayList<>();
        //获取角色集合
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //存入角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取权限集合
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //存入权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }

        }


        return new org.springframework.security.core.userdetails.User(userUsername,password,list);
    }

}
